package com.nineclock.auth.processor;

import com.nineclock.auth.entity.IntegrationAuthenticationEntity;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 *  验证码模式的 认证处理器
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Component
public class SmsAuthenticationProcessor implements AuthenticationProcessor {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    SysUserFeign userFeign;
    @Override
    public SysUserDTO authenticate(IntegrationAuthenticationEntity entity) {
        //从 请求中获取 参数
        String mobile = entity.getAuthParameter("mobile");
        String password = entity.getAuthParameter("password");
        if(mobile == null || password == null){
            throw new NcException(ResponseEnum.INVALID_USERNAME_PASSWORD);
        }
        //根据手机号 远程调用系统微服务获取 用户对象
        SysUserDTO userDTO = userFeign.queryUser(mobile).getData();
        if(userDTO == null){
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }

        //从redis获取 对应的验证码
        String key = SMSConstant.SMS_LOGIN_KEY_PREFIX + mobile;
        String code = redisTemplate.boundValueOps(key).get();
        //把 验证码的 密文 存储到userDTO中
        userDTO.setPassword(new BCryptPasswordEncoder().encode(code));

        return userDTO;
    }

    /**
     * 判断是否使用验证码处理器
     * @param entity
     * @return
     */
    @Override
    public boolean support(IntegrationAuthenticationEntity entity) {
        if( entity != null &&  "sms".equalsIgnoreCase(entity.getAuthType())){
            return true;
        }
        return false;
    }
}
